package jmind.core.selenium;

import com.google.common.collect.Maps;
import jmind.base.util.DataUtil;
import jmind.base.util.RandUtil;
import jmind.core.http.HttpClient;
import jmind.core.http.HttpClient4;
import jmind.core.image.ImageUtil;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * description:
 *
 * @author weibo.xie
 * @date : create in 11:48 上午 2021/8/10
 */
public class SeleniumZGCX {

    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver", "/Users/weibo/soft/chromedriver");
        SeleniumZGCX zgcx = new SeleniumZGCX();

        zgcx.getLicenseNo(5,"chaxdfdf","11");



    }


    public String getLicenseNo(int attempts,String name,String prov)  {
        String licenseNo=null;
        WebDriver driver = new ChromeDriver();
        try {

            driver.get("http://zgcx.nhc.gov.cn:9090/unit/index");
            driver.findElement(By.name("Unit_Name")).sendKeys(name);
            WebElement element = driver.findElement(By.name("Prov"));
            new Select(element).selectByValue(prov);
            int i = 0;
            while (i < attempts) {
                boolean b = checkCode(driver, i++);
                if (b)
                    break;
            }

            if(i>=attempts){
                System.err.println("验证码识别失败，尝试错误 "+attempts);
            }



            try {
                WebElement detail = driver.findElement(By.linkText("浏览"));
                detail.click();
                licenseNo = getLicenseNo(driver);
            }catch (NoSuchElementException e){
                System.err.println("未查询到结果");
                System.err.println();
                System.err.println(driver.getPageSource());
            }



        } finally {
            driver.quit();
        }

        return licenseNo;

    }

    private String getLicenseNo(WebDriver driver) {
        String s = null;
        try {
            TimeUnit.SECONDS.sleep(1+RandUtil.nextInt(3));
            String currentHandle = driver.getWindowHandle();
        for(String handle:driver.getWindowHandles() ){
            if(!handle.equals(currentHandle)){
                driver.switchTo().window(handle);
                break;
            }
        }
            System.err.println("cu1="+driver.getCurrentUrl());
      //  driver.get("http://zgcx.nhc.gov.cn:9090/Unit/Details/5dd4c387ebf548eb82ae8a32448f1ae6-637646321572581124-226B89760505950785F2B7E53B6031BB");

        List<WebElement> elements = driver.findElement(By.className("details_co")).findElements(By.className("row"));
        for (WebElement element : elements) {
            List<WebElement> div = element.findElements(By.tagName("div"));
            if (div.size() == 2) {
                if (div.get(0).getText().contains("登记号")) {
                    s = div.get(1).getText();
                    break;
                }
            }
        }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return s;
    }

    private static HttpClient  httpClient=new HttpClient4();

    private boolean checkCode(WebDriver driver, int attempts)  {
        WebElement imgCaptcha = driver.findElement(By.id("imgCaptcha"));
        String imageBase64 = imgCaptcha.getScreenshotAs(OutputType.BASE64);
        ImageUtil.base642Image(imageBase64, String.format("/Users/weibo/Downloads/a/captcha%s.png", attempts));
        String code = getCode(imageBase64);
        System.err.println(attempts+"-----"+code);
        driver.findElement(By.name("Check_Code")).sendKeys(code);

        WebElement button = driver.findElement(By.tagName("button").className("btn-block"));
        button.submit();

        try {
            TimeUnit.SECONDS.sleep(1+RandUtil.nextInt(3));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        List<WebElement> codeErrors = driver.findElements(By.className("validation-summary-errors"));
       // driver.findElement(By.className("text-danger"));

        try{
            List<WebElement> elements = driver.findElements(By.linkText("浏览"));
            System.err.println("浏览="+elements.size());
        }catch (Exception e){
            e.printStackTrace();
        }
        if(DataUtil.isEmpty(codeErrors)){
            return true;
        }

        if (codeErrors.get(0).getText().contains("验证码输入错误")) {
            return false;
        }
        return true;
    }

    private String getCode(String imageBase64){
        Map<String,String> params= Maps.newHashMap();
        params.put("code",imageBase64);
        Map<String,String> headers= Maps.newHashMap();
        headers.put("X-XSRF-TOKEN","1234567qwert");
        headers.put("Cookie","XSRF-TOKEN=1234567qwert");
        String code = httpClient.post("http://11.158.114.167:7001/op/getCode",params,"UTF-8",0,headers );
        return code;
    }
}